//
//  MCConsumeViewItemOneController.m
//  ERP
//
//  Created by QA on 15/12/11.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCConsumeViewItemOneController.h"

#import "WebServiceCommonRequest.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"
#import "StringAxisValueFormatter.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"
#import "AutoTextTableViewCell.h"
#import "MCConsumeOneViewCell.h"
#import "DateTimeFormat.h"
#import "GEObjectButton.h"

#import "Charts-Swift.h"
#import "MJRefresh.h"
#import "GEDateFromatter.h"
#import "MCConsumeDetailViewController.h"

@interface MCConsumeViewItemOneController ()

@property (nonatomic,strong) NSMutableArray *stateData;
@property (nonatomic,assign) NSInteger stateContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@end

@implementation MCConsumeViewItemOneController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"原材消耗_材料消耗"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.stateData = [NSMutableArray array];
    
    //设置默认搜索时间(本月)
    NSString *time = [GEDateFromatter formmatTimeDate:[NSDate date] format:@"yyyy-MM"];
    self.searchStartTime = [NSString stringWithFormat:@"%@-01",time];
    self.searchEndTime = [GEDateFromatter formmatTimeDate:[NSDate date]];
    
    //获取数据
    [self getJobOrderInfoIsReresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateTableStartTime:(NSString*)startTime endTime:(NSString*)endTime
{
    self.searchStartTime = startTime;
    self.searchEndTime = endTime;
    
    [self.stateData removeAllObjects];
    [self.tableView removeAllSaveCell];
    
    self.stateContentState = 0;
    [self.tableView reloadData];
    [self getJobOrderInfoIsReresh];
}

#pragma mark - 网络获取任务单

- (void)getJobOrderInfoIsReresh
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCL_DYXH_CL_LIST20160129"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"开始日期" value:self.searchStartTime];
    [content addParameterKey:@"截止日期" value:self.searchEndTime];
    
    //设置站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    [content setStationID:[model.stationId integerValue]];

    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];

        if(firstArray && firstArray.count>0){
            [self.stateData removeAllObjects];
            [self.stateData addObjectsFromArray:firstArray];
            self.stateContentState = 3;
        } else {
            self.stateContentState = 1;
        }
        [self.tableView reloadData];

    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];

    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
    }];
}

#pragma mark - 通用模板

- (void)drawExplainMarkView:(UIView*)contentView data:(NSArray*)data color:(NSArray*)color yValue:(CGFloat)yValue offset:(CGFloat)offset
{
    CGFloat itemWidth = contentView.frame.size.width / data.count - offset;
    for(int i=0; i<data.count; i++){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(offset*(i+1) + i*itemWidth, yValue, 15, 15)];
        view.backgroundColor = color[i];
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 2.0;
        [contentView addSubview:view];
        
        UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(i*itemWidth + offset*(i+1) + 18, yValue + 2, itemWidth - 18, 10)];
        lable.text = data[i];
        lable.font = [UIFont systemFontOfSize:14];
        [contentView addSubview:lable];
    }
}

- (void)materialChargeInCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *valueArray = [cell.objectValue firstObject];
    NSString *startTime = [self.searchStartTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTime = [self.searchEndTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    
    //绘制标题
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, SuperWidth - 40, 22)];
    titleLable.text = @"材料消耗误差率分析(%)";
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:titleLable];
    
    //绘制标题
    UIButton *subLable = [[UIButton alloc] initWithFrame:CGRectMake(20, 30, SuperWidth - 40, 22)];
    subLable.titleLabel.textColor = [UIColor darkGrayColor];
    [subLable setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    subLable.titleLabel.font = [UIFont systemFontOfSize:13];
    subLable.titleLabel.textAlignment = NSTextAlignmentCenter;
    subLable.userInteractionEnabled = NO;
    [subLable setTitle:[NSString stringWithFormat:@"以下为%@-%@数据",startTime,endTime] forState:UIControlStateNormal];
    [cell.contentView addSubview:subLable];
    
    BarChartView *_chartView = [[BarChartView alloc] initWithFrame:CGRectMake(5, 50, SuperWidth - 10, 240)];
//    _chartView.descriptionText = @"";
    _chartView.noDataText = @"暂无数据";
    
    _chartView.drawBarShadowEnabled = NO;
    _chartView.drawValueAboveBarEnabled = YES;
    _chartView.pinchZoomEnabled = NO;
    _chartView.drawGridBackgroundEnabled = NO;
    
    ChartXAxis *xAxis = _chartView.xAxis;
    xAxis.labelPosition = XAxisLabelPositionBottom;
    xAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    xAxis.drawGridLinesEnabled = NO;
    xAxis.drawLabelsEnabled = YES;
    
    ChartYAxis *leftAxis = _chartView.leftAxis;
    leftAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    leftAxis.spaceTop = 0.15;
    
    ChartYAxis *rightAxis = _chartView.rightAxis;
    rightAxis.drawGridLinesEnabled = NO;
    rightAxis.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
    rightAxis.spaceTop = 0.15;
    
    ChartLegend *l = _chartView.legend;
    l.horizontalAlignment = ChartLegendHorizontalAlignmentCenter;
    l.verticalAlignment = ChartLegendVerticalAlignmentBottom;
    l.orientation = ChartLegendOrientationHorizontal;
    l.form = ChartLegendFormSquare;
    l.formSize = 9.0;
    l.font = [UIFont systemFontOfSize:11.f];
    l.xEntrySpace = 4.0;
    
    [self setMixtureRatioChartDataChart:_chartView data:valueArray];
    [cell.contentView addSubview:_chartView];
    [_chartView animateWithXAxisDuration:2.0 yAxisDuration:2.0];
}

- (void)setMixtureRatioChartDataChart:(BarChartView *)chartView data:(NSArray*)array
{
    NSMutableArray *xVals = [[NSMutableArray alloc] init];
    NSMutableArray *entries = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < array.count; i++)
    {
        NSDictionary *mDictionary = [array objectAtIndex:i];
        NSString *name = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
        CGFloat value = [mDictionary objectFormatFloatForKey:@"误差率"];
        
        [xVals addObject:name];
        [entries addObject:[[BarChartDataEntry alloc] initWithX:i y:value]];
    }
    
    //设置底部显示文字
    chartView.xAxis.granularity = 1.0; // only intervals
    chartView.xAxis.valueFormatter = [[StringAxisValueFormatter alloc] initWithData:xVals];
    
    NSNumberFormatter *leftAxisFormatter = [[NSNumberFormatter alloc] init];
    leftAxisFormatter.minimumFractionDigits = 0;
    leftAxisFormatter.maximumFractionDigits = 1;
    leftAxisFormatter.negativeSuffix = @"%";
    leftAxisFormatter.positiveSuffix = @"%";
    
    BarChartDataSet *set = [[BarChartDataSet alloc] initWithValues:entries label:@"误差率(%)"];
    [set setColor:[UIColor colorWithRed:240/255.f green:120/255.f blue:124/255.f alpha:1.f]];
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set];
    
    BarChartData *data = [[BarChartData alloc] initWithDataSets:dataSets];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
    [data setValueFormatter:[[ChartDefaultValueFormatter alloc] initWithFormatter:leftAxisFormatter]];
    [data setDrawValues:YES];
    data.barWidth = 0.8f;
    
    chartView.data = data;
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 1) {
        if(self.stateContentState == 0) return 1;
        else if(self.stateContentState == 1) return 1;
        else if(self.stateContentState == 2) return 1;
        else if(self.stateContentState == 3) return self.stateData.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        //绘制图表数据
        GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (progressBarCell == nil) {
            NSString *identifierBar = [NSString stringWithFormat:@"MCGEProgressBarTableViewCell%ld",indexPath.section];
            progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
            progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
        }
        
        //存在数据绘制图表
        if (progressBarCell.objectValue) {
            NSString *identifier = [NSString stringWithFormat:@"MCChargeInDetailViewController%ld",(long)indexPath.section];
            GEObjectValueTableViewCell *cell = [self.tableView getCellViewKey:identifier];
            if (cell == nil) {
                cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                [self.tableView setCellView:cell key:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.objectValue = progressBarCell.objectValue;
                [self materialChargeInCell:cell indexPath:indexPath];
            }
            return cell;
        }
        
        NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
        [parameter setObject:self.searchStartTime forKey:@"开始日期"];
        [parameter setObject:self.searchEndTime forKey:@"截止日期"];
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"YCL_DYXH_CL_LIST20160129" parameter:parameter index:indexPath.section];
        return progressBarCell;
    
    } else if (indexPath.section == 1) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.stateContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 26.5);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"没有进料信息";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载数据失败，点击重试";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            return cell;
            
        } else {
            NSString *identifier = [NSString stringWithFormat:@"MCConsumeOneViewCell"];
            MCConsumeOneViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[MCConsumeOneViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            //实际消耗用量
            NSDictionary *mDictionary = [self.stateData objectAtIndex:indexPath.row];
            cell.titleLabel.text = [mDictionary objectFormatStringForKey:@"材料名称" defaults:@"未知"];
            cell.sjxhLabel.text = [mDictionary objectFormatFloatStringForKey:@"实际消耗用量" retain:1 except:10000 exceptFormat:@"%@万吨" format:@"%@吨"];
            
            NSString *wczString = [mDictionary objectFormatFloatStringForKey:@"误差值" retain:1 except:10000 exceptFormat:@"%@万吨" format:@"%@吨"];
            NSString *wcblString = [mDictionary objectFormatFloatStringForKey:@"误差率" retain:1 format:@"%@%%"];
            
            cell.wczLabel.text = [NSString stringWithFormat:@"%@ (%@)",wczString,wcblString];
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    if (section == 0) return view;
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if(section == 0){
        lable.text = @"材料消耗误差分析";
    } else if (section == 1) {
        lable.text = @"材料消耗明细";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) return 0.5;
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return 290;
    } else if(indexPath.section == 1){
        if(self.stateContentState == 3) return 54;
        else return 55;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 2){
        if(self.stateContentState == 2) {//加载失败执行
            self.stateContentState = 0;
            [self.tableView reloadData];
            [self getJobOrderInfoIsReresh];
        }
    }
}

@end

